﻿using Lamex.Base;
using Lamex.SystemManager.BLL;
using Lamex.Library;
using Lamex.SystemManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lamex.Common;
using DevExpress.Data.Mask;
using Lamex.ControlsUI;

namespace Lamex.SystemManager.UI
{
    public partial class frmOrgaStruct : frmBaseChild
    {
        public frmOrgaStruct()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmOrgaStruct_Load);
        }

        private void frmOrgaStruct_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            RefreshTreeView();
            InitDictItem();
            

        }
        private void InitDictItem()
        {
            //初始化分类
            string[] enumNames = Lamex.Common.EnumHelper.GetMemberNames<OUCategoryEnum>();
            this.txtCategory.Properties.Items.Clear();
            foreach (string item in enumNames)
            {
                this.txtCategory.Properties.Items.Add(item);
            }
        }

        private string currentID = string.Empty;
        private void butMainSave_Click(object sender, EventArgs e)
        {
            #region 验证用户输入
            if (this.txtName.Text == "")
            {
                MessageBox.Show ("机构名称不能为空");
                this.txtName.Focus();
                return;
            }
            else if (this.ucDept.Text == "")
            {
                MessageBox.Show("上级机构不能为空");
                this.ucDept.Focus();
                return;
            }

            #endregion

            if (!string.IsNullOrEmpty(currentID))
            {
                try
                {
                    #region 检查重复
                    int id = Convert.ToInt32(currentID);
                    string filter = string.Format("Name='{0}' AND PID={1} AND ID <> '{2}' ", this.txtName.Text, this.ucDept.Value, id);
                    //bool isExist = BaseFactory<tb_OrgStucture>.Instance.IsExistRecord(filter);
                    //if (isExist)
                    //{
                    //    MessageBox.Show("组织机构名称已存在！");
                    //    this.txtName.Focus();
                    //    return;
                    //}
                    #endregion

                    tb_OrgStuctureInfo info = BaseFactory<tb_OrgStucture>.Instance.GetEntriyList(" 1=1 AND  ID = '" + currentID + "' ").FirstOrDefault();
                    if (info != null)
                    {
                        info = SetOUInfo(info);
                        BaseFactory<tb_OrgStucture>.Instance.Update(info);

                        RefreshTreeView();
                    }
                }
                catch (Exception ex)
                {
                    //LogTextHelper.Error(ex);
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                #region 检查重复
                string filter = string.Format("Name='{0}' AND PID={1} ", this.txtName.Text, this.ucDept.Value);
                //bool isExist = BaseFactory<tb_OrgStucture>.Instance.IsExistRecord(filter);
                //if (isExist)
                //{
                //    MessageBox.Show("组织机构名称已存在！");
                //    this.txtName.Focus();
                //    return;
                //}
                #endregion

                tb_OrgStuctureInfo info = new tb_OrgStuctureInfo();
                info = SetOUInfo(info);
                info.Creator = Loginer.CurrentUser.AccountName ;
                info.Creator_ID =Loginer.CurrentUser.Account;
                info.CreateTime = DateTime.Now;

                try
                {
                    BaseFactory<tb_OrgStucture>.Instance.Insert(info);
                    RefreshTreeView();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void RefreshTreeView()
        {
            treeView.Nodes.Clear();
            treeView.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;
            Globle gc = new Globle();
            tb_OrgStuctureInfo groupInfo = gc.GetMyTopGroup(Loginer.CurrentUser.Account);
            if (groupInfo != null)
            {
                TreeNode topnode = new TreeNode();
                topnode.Text = groupInfo.Name;
                topnode.Name = groupInfo.ID.ToString();
                topnode.Tag = groupInfo.ID;
                topnode.ImageIndex = gc.GetImageIndex(groupInfo.Category);
                topnode.SelectedImageIndex = gc.GetImageIndex(groupInfo.Category);
                this.treeView.Nodes.Add(topnode);

                List<OUNodeInfo> list = BaseFactory<tb_OrgStucture>.Instance.GetTreeByID(groupInfo.ID);
                AddOUNode(list, topnode);
            }

            Cursor.Current = Cursors.Default;
            treeView.EndUpdate();
            this.treeView.ExpandAll();
        }

        private void AddOUNode(List<OUNodeInfo> list, TreeNode parentNode)
        {
            Globle gc = new Globle();
            foreach (OUNodeInfo ouInfo in list)
            {
                TreeNode ouNode = new TreeNode();
                ouNode.Text = ouInfo.Name;
                ouNode.Name = ouInfo.ID.ToString();
                ouNode.Tag = ouInfo.ID;
                //if (ouInfo.Deleted)
                //{
                //    ouNode.ForeColor = Color.Red;
                //}
                ouNode.ImageIndex = gc.GetImageIndex(ouInfo.Category);
                ouNode.SelectedImageIndex = gc.GetImageIndex(ouInfo.Category);
                parentNode.Nodes.Add(ouNode);

                AddOUNode(ouInfo.Children, ouNode);
            }
        }
        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                string id = e.Node.Name;
                tb_OrgStuctureInfo info = BaseFactory<tb_OrgStucture>.Instance.GetEntriyList(" 1=1 and ID = '" + id + "'").FirstOrDefault();

                if (info != null)
                {
                    currentID = id.ToString();

                    this.txtName.Text = info.Name;
                    this.txtRemark.Text = info.Note;
                    this.txtAddress.Text = info.Address;
                    this.txtSort.Text = info.SortCode;
                    this.txtNo.Text = info.HandNo;
                    this.txtOutPho.Text = info.OuterPhone;
                    this.txtInnerPho.Text = info.InnerPhone;
                    this.txtCategory.Text = info.Category;
                    this.txtCreateBy.Text = info.Creator;
                    this.txtCreateDate.Text = info.CreateTime.ToString();

                    tb_OrgStuctureInfo info2 = BaseFactory<tb_OrgStucture>.Instance.GetEntriyList(" 1=1 and ID='" + info.PID + "'").FirstOrDefault();
                    if (info2 != null)
                    {
                        this.ucDept.Value = info.PID.ToString();
                    }
                    else
                    {
                        this.ucDept.Value = "-1";
                    }

                    //如果是公司管理员，不能编辑公司的信息
                    //if (Loginer.CurrentUser.CompanyID == currentID &&
                    //    Portal.gc.UserInRole(RoleInfo.CompanyAdminName))
                    //{
                    //    this.btnSave.Enabled = false;
                    //}
                    //else
                    //{
                    //    this.btnSave.Enabled = true;
                    //}

                    int intID = Convert.ToInt32(id);
                    RefreshUsers(intID);
                    //RefreshRoles(intID);
                }
            }
        }
        // <summary>
        /// 记录用户的选择情况
        /// </summary>
        Dictionary<string, string> SelectUserDict = new Dictionary<string, string>();
        private void RefreshUsers(int id)
        {
            SelectUserDict = new Dictionary<string, string>();

            this.lvwUser.BeginUpdate();
            this.lvwUser.Items.Clear();
            List<TUserInfo> list = BaseFactory<TUser>.Instance.GetEntriyList(" 1=1 and Dept_ID='" + id + "'");
            foreach (TUserInfo info in list)
            {
                string name = string.Format("{0}（{1}）", info.UserName, info.Account);
                ListItem item = new ListItem(name, info.isid.ToString());
                this.lvwUser.Items.Add(item);

                if (!SelectUserDict.ContainsKey(info.isid.ToString()))
                {
                    SelectUserDict.Add(info.isid.ToString(), name);
                }
            }
            if (this.lvwUser.Items.Count > 0)
            {
                this.lvwUser.SelectedIndex = 0;
            }
            this.lvwUser.EndUpdate();
        }
        private tb_OrgStuctureInfo SetOUInfo(tb_OrgStuctureInfo info)
        {
            info.Name = this.txtName.Text;
            info.Note = this.txtRemark.Text;
            info.Address = this.txtAddress.Text;
            info.InnerPhone = this.txtInnerPho.Text;
            info.OuterPhone = this.txtOutPho.Text;
            info.HandNo = this.txtNo.Text;
            info.SortCode = this.txtSort.Text;
            info.Category = this.txtCategory.Text;
            info.Editor = Loginer.CurrentUser.AccountName;
            info.Editor_ID = Loginer.CurrentUser.Account;
            info.EditTime = DateTime.Now;
            info.PID = int.Parse(this.ucDept.Value.ToString());

            tb_OrgStuctureInfo pInfo = BaseFactory<tb_OrgStucture>.Instance.GetEntriyList(" 1=1 and ID='" + info.PID + "'").FirstOrDefault();
            if (pInfo != null)
            {
                //pInfo.Category == "集团" ||
                if (pInfo.Category == "公司")
                {
                    info.Company_ID = pInfo.ID.ToString();
                    info.CompanyName = pInfo.Name;
                }
                else if (pInfo.Category == "部门" || pInfo.Category == "工作组")
                {
                    info.Company_ID = pInfo.Company_ID;
                    info.CompanyName = pInfo.CompanyName;
                }
            }
            //info.CurrentLoginUserId = Portal.gc.UserInfo.ID.ToString();
            return info;
        }

        private void butAddNew_Click(object sender, EventArgs e)
        {
            ClearInput();
            currentID = "";

            TreeNode node = this.treeView.SelectedNode;
            if (node != null && node.Tag != null)
            {
                this.ucDept.Value = node.Tag.ToString();
            }

            this.txtName.Focus();
        }
        private void ClearInput()
        {
            this.txtName.Text = "";
            this.txtRemark.Text = "";
            this.txtAddress.Text = "";
            this.txtNo.Text = "";
            //this.txtSortCode.Text = "";
            this.txtCreateBy.Text = Loginer.CurrentUser.Account;
            this.txtCreateDate.Text = DateTime.Now.ToString();
            this.txtInnerPho.Text = "";
            this.txtOutPho.Text = "";

            //this.lvwRole.Items.Clear();
            this.lvwUser.Items.Clear();

            InitDictItem();
        }

        private void ToolStripMenuRefresh_Click(object sender, EventArgs e)
        {
            RefreshTreeView();
        }
    }
}
